import { ScrollView, View, Text, Image } from '@tarojs/components';
import React, { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { connect } from 'react-redux';
import './index.less';
import * as T from './types';
import actions from './actions';
import { store2Props } from './selectors';
import moment from 'dayjs';
import Blank from '@/pages/common/blank';
import notdataImg from '@/assets/image/none/none.png';
import banner from '@/assets/image/myPost/banner.png';
import Activity from '@/assets/image/myPost/Activity.png';

actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      refresherTriggered: false,
      selectDistance: Taro.getStorageSync('selectDistance') || {},
      tabList: [
        { status: 1, text: '报名中' },
        { status: 2, text: '报名结束' },
        { status: 3, text: '活动中' },
        { status: 4, text: '活动结束' },
      ],
      curNow: 1, //tab状态,对应处理状态status
    };
  }

  componentDidMount() { }

  componentDidShow() {
    this.props.actions.init();
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  changeTabs(item) {
    let { selectDistance } = this.state;
    let { user } = Taro.getStorageSync('b2b-wechat@login')
    this.setState({ curNow: item.status }, () => {
      let params = {
        userId: user.id,
        pageNum: 1,
        status: item.status,
        communityCode: selectDistance.code,
      };
      this.props.actions.action.commonChange('main.myActiveList', []);
      this.props.actions.action.commonChange('main.totalPages', 1);
      this.props.actions.action.findeActiveList(params);
    });
  }

  tabList(list) {
    let listView = [];
    let { curNow } = this.state;
    list.map((item) => {
      listView.push(
        <View
          className="t_view"
          onClick={() => {
            this.changeTabs(item);
          }}
        >
          <Text className={curNow == item.status ? 't_a_text' : 't_text'}>{item.text}</Text>
          <View className={curNow == item.status ? 't_a_border' : 't_border'}></View>
        </View>,
      );
    });
    return listView;
  }

  returnActiveType(type) {
    let {
      main: { activeType },
      actions: { action },
    } = this.props;
    let name = '';
    let keys = Object.keys(activeType);
    for (let i = 0; i < keys.length; i++) {
      if (type == keys[i]) {
        name = activeType[keys[i]];
      }
    }
    return name;
  }

  renderList(list) {
    let listView = [];
    let { curNow } = this.state;
    list.map((item, index) => {
      let imgfirst = '';
      if (item.refImage.length > 0) {
        imgfirst = item.refImage[0].imageUrl;
      }
      listView.push(
        <View className="activeMain">
          <View
            onClick={(e) => {
              e.stopPropagation();
              Taro.navigateTo({
                url: '/pages/package-C/activity/detail/index?id=' + item.id,
              });
            }}
            style={{
              width: '100%',
              borderRadius: '16rpx',
            }}
          >
            <View
              style={{
                borderRadius: '10rpx',
                backgroundColor: '#fff',
              }}
            >
              <View
                style={{
                  backgroundColor: '#fff',
                  borderRadius: 5,
                  position: 'relative',
                }}
              >
                {item.refImage.length > 0 ? (
                  <Image
                    style={{
                      width: '100%',
                      height: '250rpx',
                      borderTopLeftRadius: '16rpx',
                      borderTopRightRadius: '16rpx',
                    }}
                    src={imgfirst}
                  />
                ) : (
                  <Image
                    style={{
                      width: '100%',
                      height: '250rpx',
                      borderTopLeftRadius: '5rpx',
                      borderTopRightRadius: '5rpx',
                    }}
                    src={banner}
                  />
                )}
                <View
                  style={{
                    flexDirection: 'row',
                    position: 'absolute',
                    zIndex: '999',
                    bottom: '20rpx',
                    width: '100%',
                    paddingLeft: '24rpx',
                    backgroundColor: 'rgba(0,0,0,0.2)',
                  }}
                >
                  <Text
                    style={{
                      color: '#fff',
                      fontSize: '21rpx',
                      letterSpacing: '2rpx',
                    }}
                  >
                    开始日期：
                    {moment(item.enrollStartDate).format('YYYY-MM-DD')}
                  </Text>
                  <Text
                    style={{
                      color: '#fff',
                      fontSize: '21rpx',
                      letterSpacing: '2rpx',
                      marginLeft: '10rpx',
                    }}
                  >
                    截止日期：
                    {moment(item.enrollEndDate).format('YYYY-MM-DD')}
                  </Text>
                </View>
              </View>
              <View
                style={{
                  position: 'absolute',
                  zIndex: '999',
                  right: '10%',
                  width: '70rpx',
                  height: '80rpx',
                }}
              >
                <Image
                  style={{
                    width: '100%',
                    height: '100%',
                  }}
                  src={Activity}
                />
                <Text
                  style={{
                    position: 'absolute',
                    top: '10rpx',
                    color: '#fff',
                    fontSize: '14px',
                    textAlign: 'center',
                    lineHeight: '16px',
                    letterSpacing: '2rpx',
                  }}
                >
                  {this.returnActiveType(item.type)}
                </Text>
              </View>
              <View className="detailBottom">
                <Text
                  style={{
                    fontSize: '32rpx',
                    fontWeight: '700',
                    color: '#000',
                  }}
                >
                  {item.title}
                </Text>
              </View>
              <View className="subBox">
                <View
                  style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'flex-start',
                  }}
                >
                  <Text
                    style={{
                      fontSize: '26rpx',
                      color: '#E43A13',
                    }}
                  >
                    {item.signUpNum}
                    <Text style={{ color: '#666', fontSize: '22rpx' }}>人参与</Text>
                  </Text>
                </View>
                <View style={{ flexDirection: 'row' }}>
                  <Text style={{ color: '#666', fontSize: '22rpx' }}>已报名</Text>
                </View>
              </View>
            </View>
          </View>
        </View>,
      );
    });
    return listView;
  }

  imgRender(imgList) {
    const imgLists = [];
    const urls = [];
    imgList.map((item, index) => {
      urls.push(item.imageUrl);
      imgLists.push(
        <View>
          <Image
            className="img"
            key={item.imageUrl}
            onClick={this.onImageClick.bind(this, item, urls)}
            src={item.imageUrl}
            mode="aspectFit"
          />
        </View>,
      );
    });
    return imgLists;
  }

  onImageClick = (item, urls) => {
    this.previewImage(item.imageUrl, urls);
  };

  previewImage = (img, files) => {
    Taro.previewImage({
      current: img, // 当前显示图片的http链接
      urls: files, // 需要预览的图片http链接列表
    });
  };

  _onScrollToLower = () => {
    let { selectDistance, curNow } = this.state;
    let { user } = Taro.getStorageSync('b2b-wechat@login')
    let {
      main: { pageNum, totalPages },
      actions: { action },
    } = this.props;
    let num = pageNum + 1;
    if (pageNum == totalPages) return;
    let params = {
      userId: user.id,
      pageNum: num,
      status: curNow,
      communityCode: selectDistance.code,
    };
    this.props.actions.action.commonChange('main.pageNum', num);
    this.props.actions.action.findeActiveList(params);
  };

  _onRefresherRefresh = () => {
    let { refresherTriggered, selectDistance, curNow } = this.state;
    let { user } = Taro.getStorageSync('b2b-wechat@login')
    if (refresherTriggered) return;
    this.setState({
      refresherTriggered: true,
    });
    let params = {
      pageNum: 1,
      communityCode: selectDistance.code,
      userId: user.id,
      status: curNow,
    };
    this.props.actions.action.commonChange('main.pageNum', 1);
    this.props.actions.action.findeActiveList(params);
    setTimeout(() => {
      this.setState({
        refresherTriggered: false,
      });
    }, 2000);
  };

  render() {
    let { tabList, refresherTriggered } = this.state;
    let {
      main: { myActiveList, pageNum, totalPages, isLoading },
      actions: { action },
    } = this.props;

    return (
      <View className="myActive">
        <View className="t_row">{this.tabList(tabList)}</View>
        <ScrollView
          className="myActive-scroll"
          onScrollToLower={this._onScrollToLower}
          refresherEnabled
          refresherTriggered={refresherTriggered}
          onRefresherPulling={this._onRefresherRefresh}
          scrollY
        >
          {myActiveList.length > 0 ? (
            this.renderList(myActiveList)
          ) : (
            <Blank
              content="还没有活动信息~"
              img={notdataImg}
              imgStyle={{ width: '400rpx', height: '400rpx' }}
              textStyle={{
                fontSize: '32rpx',
                color: '#999999',
                textAlign: 'center',
                marginTop: '40rpx',
              }}
            />
          )}
          {myActiveList.length != 0 && pageNum != totalPages && <View className="status">加载中</View>}
          {!isLoading && myActiveList.length != 0 && pageNum == totalPages && (
            <View className="status">已经到底了~</View>
          )}
        </ScrollView>
      </View>
    );
  }
}
